package utils;

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import java.util.Map;

/**
 * Json<==>Obj 工具类
 */
public class JsonUtil {
	//Obj转String
	public static String parseObject(final Object object) {
		ObjectMapper om=new ObjectMapper();
		String ret=null;
		try {
			ret=om.writeValueAsString(object);
		} catch (Exception e) {
			LogUtil.logerror("对象转换json字符串失败", e);
		}
		return ret;
	}

	//把json字符串转化为POJO对象
	public static  Object readJson2Entity(String jsonstr,Class<?> oclass){
		try {
			ObjectMapper om = new ObjectMapper();
	        Object acc = om.readValue(jsonstr, oclass);
	        return acc;
	    } catch (Exception e) {
	    	LogUtil.logerror("json字符串转换对象失败", e);
	    	LogUtil.logerror("失败字符串为："+jsonstr);
	    }
		return null;
	}
	
	//把json字符串转化为Map对象
	public static Map paseJson2Map(String string) throws Exception{
		try {
			ObjectMapper mapper = new ObjectMapper(); 
			return mapper.readValue(string, Map.class);
		} catch (Exception e) {
			throw new  Exception(e.getMessage());
		}
	}

	//将json array反序列化为对象
	public static <T> T arrayToList(String json, TypeReference<T> jsonTypeReference) {
		try {
			if(json == null){
				return null;
			}
			ObjectMapper om = new ObjectMapper();
			return (T) om.readValue(json, jsonTypeReference);
		} catch (Exception e) {
			LogUtil.logerror("json字符串转换对象失败", e);
			LogUtil.logerror("失败字符串为："+json);
		}
		return null;
	}

}
